package com.fishery.message.service.impl;

import cn.ucloud.common.pojo.Account;
import cn.ucloud.common.pojo.BaseResponseResult;
import cn.ucloud.usms.client.DefaultUSMSClient;
import cn.ucloud.usms.client.USMSClient;
import cn.ucloud.usms.model.SendUSMSMessageParam;
import cn.ucloud.usms.model.SendUSMSMessageResult;
import cn.ucloud.usms.pojo.USMSConfig;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fishery.message.service.MsmService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 白sa能
 * @className
 * @date Created in 10:20 AM 1/14/21
 * @package com.fishery.message.service.impl
 * @Description
 */
@Service
public class MsmServiceImpl implements MsmService {

    private USMSClient client;

    private SendUSMSMessageParam param;

    @Value("${aliyun.accessKeyID}")
    private String AccessKey;

    @Value("${aliyun.accessSecret}")
    private String AccessSecret;

    @Value("${aliyun.signName}")
    private String SignName;

    @Value("${aliyun.changeMessageTemplate}")
    private String ChangeMessageTemplate;

    @Value("${aliyun.loginMessageTemplate}")
    private String LoginMessageTemplate;

    @Value("${aliyun.registerMessageTemplate}")
    private String RegisterMessageTemplate;

    @Value("${aliyun.remindMessageTemplate}")
    private String RemindMessageTemplate;

    /**
     *
     * @param param
     * @param phone
     * @param type
     * @return
     */
    @Override
    public boolean sendVerify(Map<String, Object> param, String phone, int type) {
        if(StringUtils.isEmpty(phone)) {
            return false;
        }
        DefaultProfile profile =
                DefaultProfile.getProfile(
                        "default",
                        AccessKey,
                        AccessSecret);
            // 地域ID, 账号的AccessKey ID, 账号AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
//        request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com"); //设置跨域域名domain(该产品的服务地址)
        request.setVersion("2017-05-25");           //设置版本(该API的版本号，格式为YYYY-MM-DD。)
        request.setAction("SendSms");               //设置要调用的接口名称，RPC风格需要获取Action参数来指定api名称
//        request.setUriPattern("/clusters");         //设置要调用的接口名称，RESTful风格需要获取PathPattern参数来指定指定RESTful路径。

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        request.putQueryParameter("SignName",SignName); //签名名称
        if(type == 1) {
            request.putQueryParameter("TemplateCode",ChangeMessageTemplate); //模板code 变更信息验证码
        } else if(type == 2) {
            request.putQueryParameter("TemplateCode",LoginMessageTemplate); //模板code 登陆验证码
        } else {
            request.putQueryParameter("TemplateCode",RegisterMessageTemplate); //模板code 注册验证码
        }
//        request.putQueryParameter("TemplateCode","SMS_209550931"); //模板code 通知短信
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据，转换json数据传递

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }

//    /**
//     *
//     * @param param
//     * @param phone
//     * @return
//     */
//    @Override
//    public boolean sendRemind(String param, String phone) {
//        if(StringUtils.isEmpty(phone)) {
//            return false;
//        }
//        DefaultProfile profile =
//                DefaultProfile.getProfile(
//                        "default",
//                        AccessKey,
//                        AccessSecret);
//        // 地域ID, 账号的AccessKey ID, 账号AccessKey Secret
//        IAcsClient client = new DefaultAcsClient(profile);
//
//        //设置相关固定的参数
//        CommonRequest request = new CommonRequest();
////        request.setProtocol(ProtocolType.HTTPS);
//        request.setMethod(MethodType.POST);
//        request.setDomain("dysmsapi.aliyuncs.com"); //设置跨域域名domain(该产品的服务地址)
//        request.setVersion("2017-05-25");           //设置版本(该API的版本号，格式为YYYY-MM-DD。)
//        request.setAction("SendSms");               //设置要调用的接口名称，RPC风格需要获取Action参数来指定api名称
////        request.setUriPattern("/clusters");         //设置要调用的接口名称，RESTful风格需要获取PathPattern参数来指定指定RESTful路径。
//
//        //设置发送相关的参数
//        request.putQueryParameter("PhoneNumbers",phone); //手机号
//        request.putQueryParameter("SignName",SignName); //签名名称
//        request.putQueryParameter("TemplateCode",RemindMessageTemplate); //模板code 通知短信
//        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));//事件
//
//        try {
//            //最终发送
//            CommonResponse response = client.getCommonResponse(request);
//            boolean ret = response.getHttpResponse().isSuccess();
//            return ret;
//        }catch(Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }

    //ucloud部分
//    public static void jsonComparator(BaseResponseResult result) {
//        try {
//            Gson gson = new GsonBuilder().serializeNulls().create();
//            JSONAssert.assertEquals(result.getResponseContent(), gson.toJson(result), JSONCompareMode.LENIENT);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void sendRemind(String phone, String time, String action) {
        client = new DefaultUSMSClient(new USMSConfig(
                new Account("e4ec47efad0708bd830121deb1e137dbb1a17af0",
                        "Tx1SRcYLRQ2KEGeYIbhBeWoXVBYmqVKgZR/NDISY9qICQ9h34acDrw==")));
        List<String> phoneNumbers = new ArrayList<>();
        //手机号
        phoneNumbers.add(phone);
        //短信模板id
        String templateId = "UTN210202B79BCC";
        param = new SendUSMSMessageParam(phoneNumbers, templateId);
        //签名内容
        param.setSigContent("仲恺农业工程学院");
        //项目id
        param.setProjectId("org-jdrgnd");
        //短信参数设置
        List<String> templateParams = new ArrayList<>();
        templateParams.add(time);
        templateParams.add(action);
        param.setTemplateParams(templateParams);

        try {
            SendUSMSMessageResult result = client.sendUSMSMessage(param);
//            jsonComparator(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
